package com.lincoln.auth;

import com.lincoln.bean.ApiCode;
import com.lincoln.bean.BaseApi;
import com.lincoln.utils.RestTemplateUtils;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@RestController
@CrossOrigin
public class AuthRibbonApplication extends BaseApi {

    public static void main(String[] args) {
        SpringApplication.run(AuthRibbonApplication.class, args);
    }

    public static String api_modele_name = "auth-app";
    public static String base_url = "http://" + api_modele_name;

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;

    /**
     * 获取用户
     *
     * @return
     */
    @PostMapping(value = "/oauth/token", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiCode token(String clientId,String clientSecret) throws Exception {
        restTemplate = new RestTemplateBuilder()
                .detectRequestFactory(false)
                .basicAuthorization(clientId, clientSecret)
                .configure(restTemplate);

        String xml = RestTemplateUtils.sendPost(restTemplate, base_url + "/oauth/token", getRequest(), String.class);
        JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
        Map<String, Object> map = xmlJSONObj.toMap();
        ApiCode apiCode = ApiCode.findCode(ApiCode.SUCCESS);
        apiCode.setData(map);
        return apiCode;
    }
}
